package org.example.cake.controller;

import com.alibaba.fastjson.JSONObject;
import org.example.cake.dto.WxLoginRequest;
import org.example.cake.dto.WxLoginResponse;
import org.example.cake.entity.Discount;
import org.example.cake.entity.User;
import org.example.cake.mapper.UserMapper;
import org.example.cake.service.DiscountService;
import org.example.cake.service.UserService;
import org.example.cake.utils.BaseResponse;
import org.example.cake.utils.JwtUtil;
import org.example.cake.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/wx")
@CrossOrigin
public class WxLoginController {
//
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DiscountService discountService;
    /**
     * 微信小程序登录
     */
//    @PostMapping("/login")
//    public ResponseEntity<BaseResponse<WxLoginResponse>> login(@RequestBody User user) throws Exception {
//        System.out.println("user = " + user);
//        JSONObject sessionInfo = WxUtil.getSessionInfo(user.getOpenid());
//        String openid = sessionInfo.getString("openid");
//        // 调用根据openid生成用户优惠券的方法
//        Discount discountForNewUser = discountService.createDiscountForNewUser(openid);
//
//        if (openid == null) throw new RuntimeException("登录失败");
//        user.setOpenid(openid);
//        // 查询或注册用户
//        userService.findOrCreateUser(user);
//        // 生成 JWT
//        String token = JwtUtil.generateToken(openid);
//        // 存入 Redis：30分钟有效期
////        redisTemplate.opsForValue().set(ProFixRedis.TOKEN + token, openid, 30, TimeUnit.MINUTES);
//        WxLoginResponse response = new WxLoginResponse(token, openid);
//        return ResponseEntity.ok(BaseResponse.success(response));
//    }
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/login")
    public ResponseEntity<BaseResponse<WxLoginResponse>> login(@RequestBody User user) throws Exception {
        System.out.println("登录用户信息: " + user);

        // 1. 获取微信openid（核心用户标识）
        JSONObject sessionInfo = WxUtil.getSessionInfo(user.getOpenid());
        String openid = sessionInfo.getString("openid");
        if (openid == null) {
            throw new RuntimeException("登录失败：无法获取用户标识");
        }
        user.setOpenid(openid);

        // 2. 查询用户是否存在（关键：判断新老用户）
        User existingUser = userMapper.selectuseropenid(openid);
        boolean isNewUser = (existingUser == null); // 不存在则为新用户

        // 3. 处理用户信息（新用户注册，老用户更新）
        if (isNewUser) {
            userMapper.insert(user); // 新用户注册
            System.out.println("新用户注册成功，openid: " + openid);
        } else {
            user.setUserid(existingUser.getUserid()); // 携带老用户ID
            userMapper.updateByPrimaryKey(user); // 更新老用户信息
            System.out.println("老用户登录，openid: " + openid);
        }

        // 4. 仅新用户生成优惠券
        Discount newUserDiscount = null;
        if (isNewUser) {
            newUserDiscount = discountService.createDiscountForNewUser(openid);
            System.out.println("为新用户生成优惠券，ID: " + newUserDiscount.getDiscountid());
            System.out.println("根据这个新生成的优惠券id查询到的优惠券信息:" + newUserDiscount);
        }

        // 5. 生成JWT令牌
        String token = JwtUtil.generateToken(openid);

        // 6. 构建响应（携带优惠券信息）
        WxLoginResponse response = new WxLoginResponse(token, openid, newUserDiscount);

        return ResponseEntity.ok(BaseResponse.success(response));
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<String> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
//            redisTemplate.delete(ProFixRedis.TOKEN + token);
            return ResponseEntity.ok("退出登录成功");
        }

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的请求");
    }

    /**
     * 获取当前登录用户信息
     */
//    @GetMapping("/userInfo")
//    public ResponseEntity<?> getUserInfo(HttpServletRequest request) {
//        String authHeader = request.getHeader("Authorization");
//
//        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Token 缺失");
//        }
//
//        String token = authHeader.substring(7);
//
//        // 检查 Redis 是否存在该 token
////        String openidFromRedis = redisTemplate.opsForValue().get(ProFixRedis.TOKEN + token);
////        if (openidFromRedis == null) {
////            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录已失效，请重新登录");
////        }
//
//        // 验证 JWT 合法性
//        if (!JwtUtil.isTokenValid(token)) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
//        }
//
//        // 获取 openid（可从 token 中解析，也可用 Redis 值）
//        String openid = JwtUtil.getOpenidFromToken(token);
//        if (openid == null) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无法获取 openid");
//        }
//
//        // 查询用户信息
//        User user = userService.findOrCreateUser(openid);
//        return ResponseEntity.ok(BaseResponse.success(user));
//    }

    /**
     * 查询用户信息
     * @param code 用户openid
     * @date 2025-07-25 谭丽娜
     * @return
     * @throws Exception
     */
    @GetMapping("/userInfo")
    public ResponseEntity<?> getUserInfo(String code) throws Exception {
        User user=userService.getUserInfo(code);
        System.out.println("code = " + code);
        return ResponseEntity.ok(BaseResponse.success(user));
    }
}
